﻿/*
 * Created by SharpDevelop.
 * User: IEscarro
 * Date: 9/1/2009
 * Time: 11:46 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using Buaya.Model;

namespace Buaya.Gui
{
	/// <summary>
	/// Description of UserForm.
	/// </summary>
	public partial class UserForm : BaseForm
	{
		IList<Module> modules = SessionFacade.FindAllModules();
		
		public UserForm() : this(new User())
		{
			
		}
		
		public UserForm(User u)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			Util.SwfUtility.SetupComboBox(comboBoxModule, modules, "Id", "Name");
			Model = u;
		}
		
		protected override void OnModelChanged(EventArgs e)
		{
			base.OnModelChanged(e);
			User u = Model as User;
			textBoxName.Text = u.Name;
			textBoxPassword.Text = u.Password;
			if (u.Id == 0) {
				foreach (Module m in modules) {
					u.AddModule(m);
				}
			}
		}
		
		void ButtonOkClick(object sender, EventArgs e)
		{
			User u = Model as User;
			u.Name = textBoxName.Text;
			u.Password = textBoxPassword.Text;
			SessionFacade.SaveOrUpdateUser(u);
			Close();
		}
		
		void ButtonCancelClick(object sender, EventArgs e)
		{
			Close();
		}
		
		void ComboBoxModuleSelectedIndexChanged(object sender, EventArgs e)
		{
			listViewAvailablePrivelges.Items.Clear();
			Module m = modules[comboBoxModule.SelectedIndex];
			foreach (ModuleCommand c in m.Commands) {
				ListViewItem li = listViewAvailablePrivelges.Items.Add(c.Name);
			}
			UserModule um = (Model as User).GetModule(m);
			foreach (UserModuleCommand c in um.Commands) {
				ListViewItem li = listViewGrantedPrivileges.Items.Add(c.ModuleCommand.Name);
			}
		}
		
		void ButtonAddClick(object sender, EventArgs e)
		{
			if (listViewAvailablePrivelges.SelectedItems.Count > 0) {
				Module module = modules[comboBoxModule.SelectedIndex];
				ModuleCommand command = module.Commands[listViewAvailablePrivelges.SelectedItems[0].Index];
				module.Commands.Remove(command);
				
				UserModule userModule = (Model as User).GetModule(module);
				userModule.AddCommand(new UserModuleCommand(command.Name, command.Command));
			}
		}
	}
}
